#include <func.h>

typedef struct 
{
    int file_len;
    char* file_name[50];
} File;
// 服务端
int main(void)
{
    int fd = socket(AF_INET, SOCK_STREAM, 0);

    int reuse = 1;
    setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse));

    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(atoi("8080"));
    addr.sin_addr.s_addr = inet_addr("127.0.0.1");

    bind(fd, (struct sockaddr*)&addr, sizeof(addr));
    listen(fd, 10);

    int sock_fd = accept(fd, NULL, NULL);

    printf("已连接用户\n");

    File file;
    while(1)
    {

        memset(&file, 0, sizeof(file));
        if(recv(sock_fd, &file, sizeof(file), 0) == 0)
            break;
        printf("文件名： %s\n", file.file_name);

        int file_fd = open(file.file_name, O_RDONLY);
        if(file_fd == -1)
        {
            printf("文件不存在\n");
            continue;
        }

        file.file_len = lseek(file_fd, 0, SEEK_END);
        printf("file_len = %d\n", file.file_len);
        lseek(file_fd, 0, SEEK_SET);
        send(sock_fd, &file, sizeof(file), 0);

        char buf[128] = {0};
        int count = read(file_fd, buf, sizeof(buf));
        printf("buf = %s\n", buf);
        send(sock_fd, buf, count, 0);
        printf("%s: 传输完成\n", file.file_name);
        
    }

    close(fd);
    close(sock_fd);
    return 0;
}

